/*
 * Created on 2005-5-8 @author wangzhiguo Description:
 */
package com.hd123.rumba.runtime;

import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;

import net.sf.hibernate.HibernateException;

import org.apache.log4j.Logger;

import com.hd123.rumba.exception.TaskExceuteException;

/**
 * @deprecated 被com.hd123.rumba.runtime.backprocess.TaskMgr及其相关类替代。
 * @author caili
 *
 */
public class Task {

  public static int STATE_NOTSCHEDULE = 0;

  public static int STATE_RUNNING = 1;

  public static int STATE_STOPED = 2;

  public static int STATE_PAUSE = 4;

  public static int STATE_TERMINATED = 5;

  public static int STATE_FINISHED = 6;

  public static int TYPE_EVERYDAY = 1;
  public static int TYPE_IMMEDIATELY = 2;
  public static int TYPE_EVERYSECONDS = 3;

  private int state = STATE_NOTSCHEDULE;

  private int LastExecuteState;

  private String LastExecuteMessage;

  private Class executeClass;

  private Calendar ExcuteTime;

  private Timer timer;

  private TaskRun taskRun;

  public int scheduleType;

  public String name;

  private int secondsToExecute; // 每隔多少秒执行

  public boolean continueRunAfterExecuteError = true;

  public Task(String name, Class executeClass) {
    this.name = name;
    this.executeClass = executeClass;
  }

  private Logger getLogger() {
    return Logger.getLogger(this.getClass());
  }

  private void reScheduleTimer() {

    if (LastExecuteState == Executeable.EXECUTESTATE_FAILED && !continueRunAfterExecuteError)
      return;
    timer = new Timer();
    taskRun = new TaskRun();
    if (scheduleType == TYPE_EVERYDAY) {
      ExcuteTime.add(Calendar.DATE, 1);
      try {
        timer.schedule(taskRun, ExcuteTime.getTime());
      } catch (Exception e) {
        getLogger().error(e.getMessage());
      }
    } else if (scheduleType == TYPE_EVERYSECONDS) {
      try {
        timer.schedule(taskRun, secondsToExecute * 1000);
      } catch (Exception e) {
        getLogger().error(e.getMessage());
      }
    }
  }

  public int startEveryday(int hour, int minute, int second) {

    if (state != STATE_NOTSCHEDULE)
      return state;
    scheduleType = TYPE_EVERYDAY;

    Calendar calNow = Calendar.getInstance();
    ExcuteTime = Calendar.getInstance();
    ExcuteTime.set(Calendar.HOUR_OF_DAY, hour);
    ExcuteTime.set(Calendar.MINUTE, minute);
    ExcuteTime.set(Calendar.SECOND, second);
    if (ExcuteTime.before(calNow))
      ExcuteTime.add(Calendar.DATE, 1);

    timer = new Timer();
    taskRun = new TaskRun();
    timer.schedule(taskRun, ExcuteTime.getTime());
    getLogger().info(name + "调度已启动: 每天" + hour + ":" + minute + ":" + second);
    state = STATE_RUNNING;
    return state;
  }

  public int startEverySeconds(int seconds) {
    if (state != STATE_NOTSCHEDULE)
      return state;
    scheduleType = TYPE_EVERYSECONDS;
    secondsToExecute = seconds;
    timer = new Timer();
    taskRun = new TaskRun();
    timer.schedule(taskRun, seconds * 1000);
    getLogger().info(name + "调度已启动: 每隔" + seconds + "(s)。");
    state = STATE_RUNNING;
    return state;
  }

  public int stop() {

    if (state == STATE_RUNNING) {
      taskRun.cancel();
      state = STATE_STOPED;
      getLogger().info(name + "已被终止");
    }
    return state;
  }

  public int pause() {
    if (state == STATE_RUNNING) {
      state = STATE_PAUSE;
      getLogger().info(name + "已被暂停");
    }
    return state;
  }

  public int reActive() {
    if (state == STATE_PAUSE) {
      state = STATE_RUNNING;
      getLogger().info(name + "已重新激活");
    }

    return state;
  }

  public int getState() {
    return state;
  }

  private class TaskRun extends TimerTask {

    public void run() {
      if (state != STATE_RUNNING)
        return;
      try {
        getLogger().info("开始执行：" + name);
        Executeable te = (Executeable) executeClass.newInstance();
        LastExecuteState = te.execute();
        getLogger().info(name + "执行成功");
        if (scheduleType == TYPE_EVERYDAY || scheduleType == TYPE_EVERYSECONDS)
          reScheduleTimer();
      } catch (IllegalAccessException e) {
        LastExecuteState = Executeable.EXECUTESTATE_FAILED;
        getLogger().error(e.getMessage());
      } catch (InstantiationException e) {
        LastExecuteState = Executeable.EXECUTESTATE_FAILED;
        getLogger().error(e.getMessage());
      } catch (TaskExceuteException e) {
        LastExecuteState = Executeable.EXECUTESTATE_FAILED;
        LastExecuteMessage = e.getMessage();
        getLogger().error(LastExecuteMessage);
      } finally {
        try {
          HibernateSession.closeSession();
        } catch (HibernateException e) {
          getLogger().error(e.getMessage());
        }
      }
    }
  }
}
